{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "name": "text_generation.ipynb",
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.8"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "t09eeeR5prIJ"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "colab_type": "code",
        "id": "GCCk8_dHpuNf",
        "colab": {}
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ovpZyIhNIgoq"
      },
      "source": [
        "# 循环神经网络（RNN）文本生成"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "hcD2nPQvPOFM"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://tensorflow.google.cn/tutorials/text/text_generation\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />在 tensorflow.google.cn 上查看</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/zh-cn/tutorials/text/text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />在 Google Colab 运行</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/zh-cn/tutorials/text/text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />在 GitHub 上查看源代码</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/zh-cn/tutorials/text/text_generation.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />下载此 notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "BwpJ5IffzRG6"
      },
      "source": [
        "本教程演示如何使用基于字符的 RNN 生成文本。我们将使用 Andrej Karpathy 在[《循环神经网络不合理的有效性》](http://karpathy.github.io/2015/05/21/rnn-effectiveness/)一文中提供的莎士比亚作品数据集。给定此数据中的一个字符序列 （“Shakespear”），训练一个模型以预测该序列的下一个字符（“e”）。通过重复调用该模型，可以生成更长的文本序列。\n",
        "\n",
        "请注意：启用 GPU 加速可以更快地执行此笔记本。在 Colab 中依次选择：*运行时 > 更改运行时类型 > 硬件加速器 > GPU*。如果在本地运行，请确保 TensorFlow 的版本为 1.11 或更高。\n",
        "\n",
        "本教程包含使用 [tf.keras](https://www.tensorflow.org/programmers_guide/keras) 和 [eager execution](https://www.tensorflow.org/programmers_guide/eager) 实现的可运行代码。以下是当本教程中的模型训练 30 个周期 （epoch），并以字符串 “Q” 开头时的示例输出：\n",
        "\n",
        "<pre>\n",
        "QUEENE:\n",
        "I had thought thou hadst a Roman; for the oracle,\n",
        "Thus by All bids the man against the word,\n",
        "Which are so weak of care, by old care done;\n",
        "Your children were in your holy love,\n",
        "And the precipitation through the bleeding throne.\n",
        "\n",
        "BISHOP OF ELY:\n",
        "Marry, and will, my lord, to weep in such a one were prettiest;\n",
        "Yet now I was adopted heir\n",
        "Of the world's lamentable day,\n",
        "To watch the next way with his father with his face?\n",
        "\n",
        "ESCALUS:\n",
        "The cause why then we are all resolved more sons.\n",
        "\n",
        "VOLUMNIA:\n",
        "O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,\n",
        "And love and pale as any will to that word.\n",
        "\n",
        "QUEEN ELIZABETH:\n",
        "But how long have I heard the soul for this world,\n",
        "And show his hands of life be proved to stand.\n",
        "\n",
        "PETRUCHIO:\n",
        "I say he look'd on, if I must be content\n",
        "To stay him from the fatal of our country's bliss.\n",
        "His lordship pluck'd from this sentence then for prey,\n",
        "And then let us twain, being the moon,\n",
        "were she such a case as fills m\n",
        "</pre>\n",
        "\n",
        "虽然有些句子符合语法规则，但是大多数句子没有意义。这个模型尚未学习到单词的含义，但请考虑以下几点：\n",
        "\n",
        "* 此模型是基于字符的。训练开始时，模型不知道如何拼写一个英文单词，甚至不知道单词是文本的一个单位。\n",
        "\n",
        "* 输出文本的结构类似于剧本 -- 文本块通常以讲话者的名字开始；而且与数据集类似，讲话者的名字采用全大写字母。\n",
        "\n",
        "* 如下文所示，此模型由小批次 （batch） 文本训练而成（每批 100 个字符）。即便如此，此模型仍然能生成更长的文本序列，并且结构连贯。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "srXC6pLGLwS6"
      },
      "source": [
        "## 设置"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "WGyKZj3bzf9p"
      },
      "source": [
        "### 导入 TensorFlow 和其他库"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "yG_n40gFzf9s",
        "colab": {}
      },
      "source": [
        "from __future__ import absolute_import, division, print_function, unicode_literals\n",
        "\n",
        "try:\n",
        "  # %tensorflow_version 仅存在于 Colab\n",
        "  %tensorflow_version 2.x\n",
        "except Exception:\n",
        "  pass\n",
        "import tensorflow as tf\n",
        "\n",
        "import numpy as np\n",
        "import os\n",
        "import time"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "EHDoRoc5PKWz"
      },
      "source": [
        "### 下载莎士比亚数据集\n",
        "\n",
        "修改下面一行代码，在你自己的数据上运行此代码。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "pD_55cOxLkAb",
        "colab": {}
      },
      "source": [
        "path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "UHjdCjDuSvX_"
      },
      "source": [
        "### 读取数据\n",
        "\n",
        "首先，看一看文本："
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "aavnuByVymwK",
        "colab": {}
      },
      "source": [
        "# 读取并为 py2 compat 解码\n",
        "text = open(path_to_file, 'rb').read().decode(encoding='utf-8')\n",
        "\n",
        "# 文本长度是指文本中的字符个数\n",
        "print ('Length of text: {} characters'.format(len(text)))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Duhg9NrUymwO",
        "colab": {}
      },
      "source": [
        "# 看一看文本中的前 250 个字符\n",
        "print(text[:250])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "IlCgQBRVymwR",
        "colab": {}
      },
      "source": [
        "# 文本中的非重复字符\n",
        "vocab = sorted(set(text))\n",
        "print ('{} unique characters'.format(len(vocab)))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "rNnrKn_lL-IJ"
      },
      "source": [
        "## 处理文本"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LFjSVAlWzf-N"
      },
      "source": [
        "### 向量化文本\n",
        "\n",
        "在训练之前，我们需要将字符串映射到数字表示值。创建两个查找表格：一个将字符映射到数字，另一个将数字映射到字符。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "y0FUEx8jjmLk",
        "colab": {}
      },
      "source": [
        "# 创建从非重复字符到索引的映射\n",
        "char2idx = {u:i for i, u in enumerate(vocab)}\n",
        "idx2char = np.array(vocab)\n",
        "\n",
        "text_as_int = np.array([char2idx[c] for c in text])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "tZfqhkYCymwX"
      },
      "source": [
        "现在，每个字符都有一个整数表示值。请注意，我们将字符映射至索引 0 至 `len(unique)`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "FYyNlCNXymwY",
        "colab": {}
      },
      "source": [
        "print('{')\n",
        "for char,_ in zip(char2idx, range(20)):\n",
        "    print('  {:4s}: {:3d},'.format(repr(char), char2idx[char]))\n",
        "print('  ...\\n}')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "l1VKcQHcymwb",
        "colab": {}
      },
      "source": [
        "# 显示文本首 13 个字符的整数映射\n",
        "print ('{} ---- characters mapped to int ---- > {}'.format(repr(text[:13]), text_as_int[:13]))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "bbmsf23Bymwe"
      },
      "source": [
        "### 预测任务"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "wssHQ1oGymwe"
      },
      "source": [
        "给定一个字符或者一个字符序列，下一个最可能出现的字符是什么？这就是我们训练模型要执行的任务。输入进模型的是一个字符序列，我们训练这个模型来预测输出 -- 每个时间步（time step）预测下一个字符是什么。\n",
        "\n",
        "由于 RNN 是根据前面看到的元素维持内部状态，那么，给定此时计算出的所有字符，下一个字符是什么？"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "hgsVvVxnymwf"
      },
      "source": [
        "### 创建训练样本和目标\n",
        "\n",
        "接下来，将文本划分为样本序列。每个输入序列包含文本中的 `seq_length` 个字符。\n",
        "\n",
        "对于每个输入序列，其对应的目标包含相同长度的文本，但是向右顺移一个字符。\n",
        "\n",
        "将文本拆分为长度为 `seq_length+1` 的文本块。例如，假设 `seq_length` 为 4 而且文本为 “Hello”， 那么输入序列将为 “Hell”，目标序列将为 “ello”。\n",
        "\n",
        "为此，首先使用 `tf.data.Dataset.from_tensor_slices` 函数把文本向量转换为字符索引流。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "mQ1jrAoVjmLu",
        "colab": {}
      },
      "source": [
        "# 设定每个输入句子长度的最大值\n",
        "seq_length = 100\n",
        "examples_per_epoch = len(text)//seq_length\n",
        "\n",
        "# 创建训练样本 / 目标\n",
        "char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)\n",
        "\n",
        "for i in char_dataset.take(5):\n",
        "  print(idx2char[i.numpy()])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-ZSYAcQV8OGP"
      },
      "source": [
        "`batch` 方法使我们能轻松把单个字符转换为所需长度的序列。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "l4hkDU3i7ozi",
        "colab": {}
      },
      "source": [
        "sequences = char_dataset.batch(seq_length+1, drop_remainder=True)\n",
        "\n",
        "for item in sequences.take(5):\n",
        "  print(repr(''.join(idx2char[item.numpy()])))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "UbLcIPBj_mWZ"
      },
      "source": [
        "对于每个序列，使用 `map` 方法先复制再顺移，以创建输入文本和目标文本。`map` 方法可以将一个简单的函数应用到每一个批次 （batch）。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "9NGu-FkO_kYU",
        "colab": {}
      },
      "source": [
        "def split_input_target(chunk):\n",
        "    input_text = chunk[:-1]\n",
        "    target_text = chunk[1:]\n",
        "    return input_text, target_text\n",
        "\n",
        "dataset = sequences.map(split_input_target)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "hiCopyGZymwi"
      },
      "source": [
        "打印第一批样本的输入与目标值："
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "GNbw-iR0ymwj",
        "colab": {}
      },
      "source": [
        "for input_example, target_example in  dataset.take(1):\n",
        "  print ('Input data: ', repr(''.join(idx2char[input_example.numpy()])))\n",
        "  print ('Target data:', repr(''.join(idx2char[target_example.numpy()])))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "_33OHL3b84i0"
      },
      "source": [
        "这些向量的每个索引均作为一个时间步来处理。作为时间步 0 的输入，模型接收到 “F” 的索引，并尝试预测 “i” 的索引为下一个字符。在下一个时间步，模型执行相同的操作，但是 `RNN` 不仅考虑当前的输入字符，还会考虑上一步的信息。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "0eBu9WZG84i0",
        "colab": {}
      },
      "source": [
        "for i, (input_idx, target_idx) in enumerate(zip(input_example[:5], target_example[:5])):\n",
        "    print(\"Step {:4d}\".format(i))\n",
        "    print(\"  input: {} ({:s})\".format(input_idx, repr(idx2char[input_idx])))\n",
        "    print(\"  expected output: {} ({:s})\".format(target_idx, repr(idx2char[target_idx])))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "MJdfPmdqzf-R"
      },
      "source": [
        "### 创建训练批次\n",
        "\n",
        "前面我们使用 `tf.data` 将文本拆分为可管理的序列。但是在把这些数据输送至模型之前，我们需要将数据重新排列 （shuffle） 并打包为批次。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "p2pGotuNzf-S",
        "colab": {}
      },
      "source": [
        "# 批大小\n",
        "BATCH_SIZE = 64\n",
        "\n",
        "# 设定缓冲区大小，以重新排列数据集\n",
        "# （TF 数据被设计为可以处理可能是无限的序列，\n",
        "# 所以它不会试图在内存中重新排列整个序列。相反，\n",
        "# 它维持一个缓冲区，在缓冲区重新排列元素。） \n",
        "BUFFER_SIZE = 10000\n",
        "\n",
        "dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)\n",
        "\n",
        "dataset"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "r6oUuElIMgVx"
      },
      "source": [
        "## 创建模型"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "m8gPwEjRzf-Z"
      },
      "source": [
        "使用 `tf.keras.Sequential` 定义模型。在这个简单的例子中，我们使用了三个层来定义模型：\n",
        "\n",
        "* `tf.keras.layers.Embedding`：输入层。一个可训练的对照表，它会将每个字符的数字映射到一个 `embedding_dim` 维度的向量。 \n",
        "* `tf.keras.layers.GRU`：一种 RNN 类型，其大小由 `units=rnn_units` 指定（这里你也可以使用一个 LSTM 层）。\n",
        "* `tf.keras.layers.Dense`：输出层，带有 `vocab_size` 个输出。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "zHT8cLh7EAsg",
        "colab": {}
      },
      "source": [
        "# 词集的长度\n",
        "vocab_size = len(vocab)\n",
        "\n",
        "# 嵌入的维度\n",
        "embedding_dim = 256\n",
        "\n",
        "# RNN 的单元数量\n",
        "rnn_units = 1024"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "MtCrdfzEI2N0",
        "colab": {}
      },
      "source": [
        "def build_model(vocab_size, embedding_dim, rnn_units, batch_size):\n",
        "  model = tf.keras.Sequential([\n",
        "    tf.keras.layers.Embedding(vocab_size, embedding_dim,\n",
        "                              batch_input_shape=[batch_size, None]),\n",
        "    tf.keras.layers.GRU(rnn_units,\n",
        "                        return_sequences=True,\n",
        "                        stateful=True,\n",
        "                        recurrent_initializer='glorot_uniform'),\n",
        "    tf.keras.layers.Dense(vocab_size)\n",
        "  ])\n",
        "  return model"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "wwsrpOik5zhv",
        "colab": {}
      },
      "source": [
        "model = build_model(\n",
        "  vocab_size = len(vocab),\n",
        "  embedding_dim=embedding_dim,\n",
        "  rnn_units=rnn_units,\n",
        "  batch_size=BATCH_SIZE)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "RkA5upJIJ7W7"
      },
      "source": [
        "对于每个字符，模型会查找嵌入，把嵌入当作输入运行 GRU 一个时间步，并用密集层生成逻辑回归 （logits），预测下一个字符的对数可能性。\n",
        "![数据在模型中传输的示意图](https://github.com/littlebeanbean7/docs/blob/master/site/en/tutorials/text/images/text_generation_training.png?raw=1)\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-ubPo0_9Prjb"
      },
      "source": [
        "## 试试这个模型\n",
        "\n",
        "现在运行这个模型，看看它是否按预期运行。\n",
        "\n",
        "首先检查输出的形状："
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "C-_70kKAPrPU",
        "colab": {}
      },
      "source": [
        "for input_example_batch, target_example_batch in dataset.take(1):\n",
        "  example_batch_predictions = model(input_example_batch)\n",
        "  print(example_batch_predictions.shape, \"# (batch_size, sequence_length, vocab_size)\")"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Q6NzLBi4VM4o"
      },
      "source": [
        "在上面的例子中，输入的序列长度为 `100`， 但是这个模型可以在任何长度的输入上运行："
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "vPGmAAXmVLGC",
        "colab": {}
      },
      "source": [
        "model.summary()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "uwv0gEkURfx1"
      },
      "source": [
        "为了获得模型的实际预测，我们需要从输出分布中抽样，以获得实际的字符索引。这个分布是根据对字符集的逻辑回归定义的。\n",
        "\n",
        "请注意：从这个分布中 _抽样_ 很重要，因为取分布的 _最大值自变量点集（argmax）_ 很容易使模型卡在循环中。\n",
        "\n",
        "试试这个批次中的第一个样本："
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "4V4MfFg0RQJg",
        "colab": {}
      },
      "source": [
        "sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)\n",
        "sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "QM1Vbxs_URw5"
      },
      "source": [
        "这使我们得到每个时间步预测的下一个字符的索引。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "YqFMUQc_UFgM",
        "colab": {}
      },
      "source": [
        "sampled_indices"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LfLtsP3mUhCG"
      },
      "source": [
        "解码它们，以查看此未经训练的模型预测的文本："
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "xWcFwPwLSo05",
        "colab": {}
      },
      "source": [
        "print(\"Input: \\n\", repr(\"\".join(idx2char[input_example_batch[0]])))\n",
        "print()\n",
        "print(\"Next Char Predictions: \\n\", repr(\"\".join(idx2char[sampled_indices ])))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LJL0Q0YPY6Ee"
      },
      "source": [
        "## 训练模型"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "YCbHQHiaa4Ic"
      },
      "source": [
        "此时，这个问题可以被视为一个标准的分类问题：给定先前的 RNN 状态和这一时间步的输入，预测下一个字符的类别。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "trpqTWyvk0nr"
      },
      "source": [
        "### 添加优化器和损失函数"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "UAjbjY03eiQ4"
      },
      "source": [
        "标准的 `tf.keras.losses.sparse_categorical_crossentropy` 损失函数在这里适用，因为它被应用于预测的最后一个维度。\n",
        "\n",
        "因为我们的模型返回逻辑回归，所以我们需要设定命令行参数 `from_logits`。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "4HrXTACTdzY-",
        "colab": {}
      },
      "source": [
        "def loss(labels, logits):\n",
        "  return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)\n",
        "\n",
        "example_batch_loss  = loss(target_example_batch, example_batch_predictions)\n",
        "print(\"Prediction shape: \", example_batch_predictions.shape, \" # (batch_size, sequence_length, vocab_size)\")\n",
        "print(\"scalar_loss:      \", example_batch_loss.numpy().mean())"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "jeOXriLcymww"
      },
      "source": [
        "使用 `tf.keras.Model.compile` 方法配置训练步骤。我们将使用 `tf.keras.optimizers.Adam` 并采用默认参数，以及损失函数。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "DDl1_Een6rL0",
        "colab": {}
      },
      "source": [
        "model.compile(optimizer='adam', loss=loss)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ieSJdchZggUj"
      },
      "source": [
        "### 配置检查点"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "C6XBUUavgF56"
      },
      "source": [
        "使用 `tf.keras.callbacks.ModelCheckpoint` 来确保训练过程中保存检查点。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "W6fWTriUZP-n",
        "colab": {}
      },
      "source": [
        "# 检查点保存至的目录\n",
        "checkpoint_dir = './training_checkpoints'\n",
        "\n",
        "# 检查点的文件名\n",
        "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt_{epoch}\")\n",
        "\n",
        "checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(\n",
        "    filepath=checkpoint_prefix,\n",
        "    save_weights_only=True)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "3Ky3F_BhgkTW"
      },
      "source": [
        "### 执行训练"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "IxdOA-rgyGvs"
      },
      "source": [
        "为保持训练时间合理，使用 10 个周期来训练模型。在 Colab 中，将运行时设置为 GPU 以加速训练。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "7yGBE2zxMMHs",
        "colab": {}
      },
      "source": [
        "EPOCHS=10"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "UK-hmKjYVoll",
        "colab": {}
      },
      "source": [
        "history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kKkD5M6eoSiN"
      },
      "source": [
        "## 生成文本"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JIPcXllKjkdr"
      },
      "source": [
        "### 恢复最新的检查点"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LyeYRiuVjodY"
      },
      "source": [
        "为保持此次预测步骤简单，将批大小设定为 1。\n",
        "\n",
        "由于 RNN 状态从时间步传递到时间步的方式，模型建立好之后只接受固定的批大小。\n",
        "\n",
        "若要使用不同的 `batch_size` 来运行模型，我们需要重建模型并从检查点中恢复权重。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "zk2WJ2-XjkGz",
        "colab": {}
      },
      "source": [
        "tf.train.latest_checkpoint(checkpoint_dir)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "LycQ-ot_jjyu",
        "colab": {}
      },
      "source": [
        "model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)\n",
        "\n",
        "model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))\n",
        "\n",
        "model.build(tf.TensorShape([1, None]))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "71xa6jnYVrAN",
        "colab": {}
      },
      "source": [
        "model.summary()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "DjGz1tDkzf-u"
      },
      "source": [
        "### 预测循环\n",
        "\n",
        "下面的代码块生成文本：\n",
        "\n",
        "* 首先设置起始字符串，初始化 RNN 状态并设置要生成的字符个数。\n",
        "\n",
        "* 用起始字符串和 RNN 状态，获取下一个字符的预测分布。\n",
        "\n",
        "* 然后，用分类分布计算预测字符的索引。把这个预测字符当作模型的下一个输入。\n",
        "\n",
        "* 模型返回的 RNN 状态被输送回模型。现在，模型有更多上下文可以学习，而非只有一个字符。在预测出下一个字符后，更改过的 RNN 状态被再次输送回模型。模型就是这样，通过不断从前面预测的字符获得更多上下文，进行学习。\n",
        "\n",
        "![为生成文本，模型的输出被输送回模型作为输入](https://github.com/littlebeanbean7/docs/blob/master/site/en/tutorials/text/images/text_generation_sampling.png?raw=1)\n",
        "\n",
        "查看生成的文本，你会发现这个模型知道什么时候使用大写字母，什么时候分段，而且模仿出了莎士比亚式的词汇。由于训练的周期小，模型尚未学会生成连贯的句子。\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "WvuwZBX5Ogfd",
        "colab": {}
      },
      "source": [
        "def generate_text(model, start_string):\n",
        "  # 评估步骤（用学习过的模型生成文本）\n",
        "\n",
        "  # 要生成的字符个数\n",
        "  num_generate = 1000\n",
        "\n",
        "  # 将起始字符串转换为数字（向量化）\n",
        "  input_eval = [char2idx[s] for s in start_string]\n",
        "  input_eval = tf.expand_dims(input_eval, 0)\n",
        "\n",
        "  # 空字符串用于存储结果\n",
        "  text_generated = []\n",
        "\n",
        "  # 低温度会生成更可预测的文本\n",
        "  # 较高温度会生成更令人惊讶的文本\n",
        "  # 可以通过试验以找到最好的设定\n",
        "  temperature = 1.0\n",
        "\n",
        "  # 这里批大小为 1\n",
        "  model.reset_states()\n",
        "  for i in range(num_generate):\n",
        "      predictions = model(input_eval)\n",
        "      # 删除批次的维度\n",
        "      predictions = tf.squeeze(predictions, 0)\n",
        "\n",
        "      # 用分类分布预测模型返回的字符\n",
        "      predictions = predictions / temperature\n",
        "      predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()\n",
        "\n",
        "      # 把预测字符和前面的隐藏状态一起传递给模型作为下一个输入\n",
        "      input_eval = tf.expand_dims([predicted_id], 0)\n",
        "\n",
        "      text_generated.append(idx2char[predicted_id])\n",
        "\n",
        "  return (start_string + ''.join(text_generated))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ktovv0RFhrkn",
        "colab": {}
      },
      "source": [
        "print(generate_text(model, start_string=u\"ROMEO: \"))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "AM2Uma_-yVIq"
      },
      "source": [
        "若想改进结果，最简单的方式是延长训练时间 （试试 `EPOCHS=30`）。\n",
        "\n",
        "你还可以试验使用不同的起始字符串，或者尝试增加另一个 RNN 层以提高模型的准确率，亦或调整温度参数以生成更多或者更少的随机预测。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Y4QwTjAM6A2O"
      },
      "source": [
        "## 高级：自定义训练\n",
        "\n",
        "上面的训练步骤简单，但是能控制的地方不多。\n",
        "\n",
        "至此，你已经知道如何手动运行模型。现在，让我们打开训练循环，并自己实现它。这是一些任务的起点，例如实现 _课程学习_ 以帮助稳定模型的开环输出。\n",
        "\n",
        "你将使用 `tf.GradientTape` 跟踪梯度。关于此方法的更多信息请参阅 [eager execution 指南](https://www.tensorflow.org/guide/eager)。\n",
        "\n",
        "步骤如下：\n",
        "\n",
        "* 首先，初始化 RNN 状态，使用 `tf.keras.Model.reset_states` 方法。\n",
        "\n",
        "* 然后，迭代数据集（逐批次）并计算每次迭代对应的 *预测*。\n",
        "\n",
        "* 打开一个 `tf.GradientTape` 并计算该上下文时的预测和损失。\n",
        "\n",
        "* 使用 `tf.GradientTape.grads` 方法，计算当前模型变量情况下的损失梯度。\n",
        "\n",
        "* 最后，使用优化器的 `tf.train.Optimizer.apply_gradients` 方法向下迈出一步。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "_XAm7eCoKULT",
        "colab": {}
      },
      "source": [
        "model = build_model(\n",
        "  vocab_size = len(vocab),\n",
        "  embedding_dim=embedding_dim,\n",
        "  rnn_units=rnn_units,\n",
        "  batch_size=BATCH_SIZE)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "qUKhnZtMVpoJ",
        "colab": {}
      },
      "source": [
        "optimizer = tf.keras.optimizers.Adam()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "b4kH1o0leVIp",
        "colab": {}
      },
      "source": [
        "@tf.function\n",
        "def train_step(inp, target):\n",
        "  with tf.GradientTape() as tape:\n",
        "    predictions = model(inp)\n",
        "    loss = tf.reduce_mean(\n",
        "        tf.keras.losses.sparse_categorical_crossentropy(\n",
        "            target, predictions, from_logits=True))\n",
        "  grads = tape.gradient(loss, model.trainable_variables)\n",
        "  optimizer.apply_gradients(zip(grads, model.trainable_variables))\n",
        "\n",
        "  return loss"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "d4tSNwymzf-q",
        "colab": {}
      },
      "source": [
        "# 训练步骤\n",
        "EPOCHS = 10\n",
        "\n",
        "for epoch in range(EPOCHS):\n",
        "  start = time.time()\n",
        "\n",
        "  # 在每个训练周期开始时，初始化隐藏状态\n",
        "  # 隐藏状态最初为 None\n",
        "  hidden = model.reset_states()\n",
        "\n",
        "  for (batch_n, (inp, target)) in enumerate(dataset):\n",
        "    loss = train_step(inp, target)\n",
        "\n",
        "    if batch_n % 100 == 0:\n",
        "      template = 'Epoch {} Batch {} Loss {}'\n",
        "      print(template.format(epoch+1, batch_n, loss))\n",
        "\n",
        "  # 每 5 个训练周期，保存（检查点）1 次模型\n",
        "  if (epoch + 1) % 5 == 0:\n",
        "    model.save_weights(checkpoint_prefix.format(epoch=epoch))\n",
        "\n",
        "  print ('Epoch {} Loss {:.4f}'.format(epoch+1, loss))\n",
        "  print ('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))\n",
        "\n",
        "model.save_weights(checkpoint_prefix.format(epoch=epoch))"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}